<html>
 <head>
  <meta charset="UTF-8">
 </head>
 <body>
  <h1 data-lake-id="H0cjA" id="H0cjA"><span data-lake-id="uef42ab91" id="uef42ab91">典型回答</span></h1>
  <ul list="u642a90a8">
   <li fid="u7fd97ec6" data-lake-id="u7555d951" id="u7555d951"><strong><span data-lake-id="ud359c3d8" id="ud359c3d8">非公平锁</span></strong><span data-lake-id="uad191416" id="uad191416">：多个线程</span><strong><span data-lake-id="u6f965e6b" id="u6f965e6b">不按照申请锁的顺序</span></strong><span data-lake-id="ubdf54321" id="ubdf54321">去获得锁，而是直接去尝试获取锁，获取不到，再进入队列等待，如果能获取到，就直接获取到锁。</span></li>
  </ul>
  <p data-lake-id="u9c2513ba" id="u9c2513ba"><br></p>
  <p data-lake-id="ua6a2a0fc" id="ua6a2a0fc"><img src="https://cdn.nlark.com/yuque/0/2024/png/5378072/1704529751249-a3586c92-9878-45da-ade4-7d79d2c3c3f5.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_41%2Ctext_SmF2YSA4IEd1IFA%3D%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10"></p>
  <ul list="udee816e7">
   <li fid="u7fd97ec6" data-lake-id="u20c6b9c4" id="u20c6b9c4"><strong><span data-lake-id="ube668ebd" id="ube668ebd">公平锁</span></strong><span data-lake-id="u2cff1b8c" id="u2cff1b8c">：多个线程</span><strong><span data-lake-id="u6bd08dee" id="u6bd08dee">按照申请锁的顺序</span></strong><span data-lake-id="u6ef6240e" id="u6ef6240e">去获得锁，所有线程都在队列里排队，这样就保证了队列中的第一个先得到锁。</span></li>
  </ul>
  <p data-lake-id="uaf765d18" id="uaf765d18"><br></p>
  <p data-lake-id="uc1b9e734" id="uc1b9e734"><img src="https://cdn.nlark.com/yuque/0/2024/png/5378072/1704529865316-b41b30f0-7c48-4726-addf-1acb96077634.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_34%2Ctext_SmF2YSA4IEd1IFA%3D%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10"></p>
  <p data-lake-id="u4045e5f0" id="u4045e5f0"><br></p>
  <p data-lake-id="u68ca0abe" id="u68ca0abe"><span data-lake-id="u971b9326" id="u971b9326">​</span><br></p>
  <p data-lake-id="u41099c9e" id="u41099c9e"><span data-lake-id="uc181806f" id="uc181806f">两种锁分别适合不同的场景中，存在着各自的优缺点，</span><strong><span data-lake-id="uc7d765cc" id="uc7d765cc">对于公平锁来说，他的优点是所有的线程都能得到资源，不会饿死在队列中。但是他存在着吞吐量会下降很多，队列里面除了第一个线程，其他的线程都会阻塞，cpu唤醒阻塞线程的开销会很大的缺点。</span></strong></p>
  <p data-lake-id="u436793e4" id="u436793e4"><span data-lake-id="ucd52812a" id="ucd52812a">​</span><br></p>
  <p data-lake-id="u18219bc1" id="u18219bc1"><span data-lake-id="u79d476dd" id="u79d476dd">而</span><strong><span data-lake-id="u92580b1a" id="u92580b1a">对于非公平锁来说，他可以减少CPU唤醒线程的开销，整体的吞吐效率会高点，CPU也不必去唤醒所有线程，会减少唤起线程的数量。但是他可能会导致队列中排队的线程一直获取不到锁或者长时间获取不到锁，活活饿死的情况。</span></strong></p>
  <p data-lake-id="ube45c6ed" id="ube45c6ed"><span data-lake-id="ub9616fd1" id="ub9616fd1">​</span><br></p>
  <h1 data-lake-id="ZqVp6" id="ZqVp6"><span data-lake-id="ubced97e4" id="ubced97e4">扩展知识</span></h1>
  <p data-lake-id="ub372dce8" id="ub372dce8"><span data-lake-id="u4a7f32f6" id="u4a7f32f6">ReentrantLock 分为公平锁和非公平锁，可以通过构造方法来指定具体类型：</span></p>
  <p data-lake-id="u94abdda1" id="u94abdda1"><span data-lake-id="u427a0330" id="u427a0330">​</span><br></p>
  <pre lang="java"><code>
//默认非公平锁
public ReentrantLock() {
	sync = new NonfairSync();
}
</code></pre>
  <p data-lake-id="u144ac717" id="u144ac717"><br></p>
  <pre lang="java"><code>
//公平锁
public ReentrantLock(boolean fair) {
	sync = fair ? new FairSync() : new NonfairSync();
}
</code></pre>
  <p data-lake-id="u8e95668a" id="u8e95668a"><span data-lake-id="u33c120dc" id="u33c120dc">​</span><br></p>
  <p data-lake-id="u0f5255cf" id="u0f5255cf"><span data-lake-id="u2de354cc" id="u2de354cc">默认一般使用</span><strong><span data-lake-id="uba9fc8ce" id="uba9fc8ce">非公平锁</span></strong><span data-lake-id="uab71fddd" id="uab71fddd">，它的效率和吞吐量都比公平锁高的多。</span></p>
  <p data-lake-id="u06830c1d" id="u06830c1d"><span data-lake-id="u3fe865cb" id="u3fe865cb">​</span><br></p>
  <h2 data-lake-id="Ky9z8" id="Ky9z8"><span data-lake-id="u50fd7654" id="u50fd7654" class="lake-fontsize-12" style="color: rgb(0, 0, 0)">reentrantLock的非公平锁实现</span></h2>
  <p data-lake-id="u55b77c73" id="u55b77c73"><span data-lake-id="ua7660b19" id="ua7660b19">​</span><br></p>
  <p data-lake-id="ua4ef5811" id="ua4ef5811"><span data-lake-id="uf271b744" id="uf271b744">非公平锁的lock的核心逻辑在NonfairSync中，具体代码如下：</span></p>
  <p data-lake-id="ub3c118c0" id="ub3c118c0"><span data-lake-id="ub3d4feb2" id="ub3d4feb2">​</span><br></p>
  <pre lang="java"><code>
/**
 * Sync object for non-fair locks
 */
static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    /**
     * Performs lock.  Try immediate barge, backing up to normal
     * acquire on failure.
     */
    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

</code></pre>
  <p data-lake-id="u921ff0f0" id="u921ff0f0"><a href="https://blog.csdn.net/weixin_39309402/article/details/106466843" target="_blank" data-lake-id="u6d691ab6" id="u6d691ab6"><span data-lake-id="u6d5b39ea" id="u6d5b39ea"><br></span></a></p>
  <p data-lake-id="ueed7e9e1" id="ueed7e9e1"><span data-lake-id="u8ced5f33" id="u8ced5f33">从代码里可以看出，lock方法执行的时候会先用cas来判断当前锁是否有线程在占用，如果cas成功，也就是成功将1设到state上去了的话，那么当时锁是没有线程在占用的，那么最后会执行将当前线程设到AbstractOwnableSynchronizer中。</span></p>
  <p data-lake-id="u88e36df7" id="u88e36df7"><span data-lake-id="ue8e4cf9a" id="ue8e4cf9a">​</span><br></p>
  <p data-lake-id="u46240f99" id="u46240f99"><span data-lake-id="u3eea8c73" id="u3eea8c73">也就是说，在非公平锁中，如果有线程尝试获取锁的时候，不会直接排队，而是先通过CAS尝试获取锁，获取到了就直接用， 获取不到再排队。</span></p>
  <h2 data-lake-id="r0NxX" id="r0NxX"><span data-lake-id="u1d060a1b" id="u1d060a1b" class="lake-fontsize-12" style="color: rgb(0, 0, 0)">reentrantLock的公平锁实现</span></h2>
  <p data-lake-id="u44b543e9" id="u44b543e9"><span data-lake-id="u0f6f207d" id="u0f6f207d">公平锁的lock的核心逻辑在FairSync中，具体代码如下：</span></p>
  <p data-lake-id="u96c4fc00" id="u96c4fc00"><span data-lake-id="u0076ed77" id="u0076ed77">​</span><br></p>
  <pre lang="java"><code>

/**
 * Sync object for fair locks
 */
static final class FairSync extends Sync {
    private static final long serialVersionUID = -3000897897090466540L;

    final void lock() {
        acquire(1);
    }

    /**
     * Fair version of tryAcquire.  Don't grant access unless
     * recursive call or no waiters or is first.
     */
    protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            if (!hasQueuedPredecessors() &amp;&amp;
                compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            if (nextc &lt; 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        return false;
    }
}
</code></pre>
  <p data-lake-id="u8b615cc3" id="u8b615cc3"><br></p>
  <p data-lake-id="u604f2005" id="u604f2005"><span data-lake-id="u7a37aea6" id="u7a37aea6">公平锁的lock方法在进行cas判断时多了一个</span><code data-lake-id="uf0ecf7c6" id="uf0ecf7c6"><span data-lake-id="ue6620472" id="ue6620472">hasQueuedPredecessors</span></code><span data-lake-id="uc686db56" id="uc686db56">的判断，它会在AQS队列中没有线程的情况下才会申请锁，而不像非公平锁一样，非公平锁一来不管AQS里是否有排队的线程就直接申请锁。</span></p>
 </body>
</html>